package com.linxz.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener2;
import android.hardware.SensorManager;
import android.widget.Toast;

/**
 * @author Linxz
 * 创建日期：2019年06月25日 09:24
 * version：v4.0.1
 * 描述：摇一摇功能
 */
public class ShakeManager {

    private Context context;

    public static ShakeManager getInstance(Context context){
        return new ShakeManager(context);
    }

    private ShakeManager(Context context){
        this.context=context;
        init();
    }

    private void init(){
        SensorManager sensorManager= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager!=null){
            Sensor sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener(new ShakeHelper(mShakeCallBack),sensor,SensorManager.SENSOR_DELAY_GAME);
        }
    }


    private ShakeCallBack mShakeCallBack=new ShakeCallBack(){
        @Override
        public void shake() {
            Toast.makeText(context,"摇一摇",Toast.LENGTH_LONG).show();
        }
    };


    @SuppressLint("NewApi")
    public static class ShakeHelper implements SensorEventListener2 {
        private ShakeCallBack mShakeCallBack;
        //速度阀值
        private int mSpeed = 14000;
        //时间间隔
        private int mInterval = 50;
        //上一次摇晃的时间
        private long mLastTime = 0L;
        //上一次的x、y、z坐标
        private float mLastX=0f;
        private float mLastY=0f;
        private float mLastZ=0f;

        public ShakeHelper(ShakeCallBack shakeCallBack){
            this.mShakeCallBack=shakeCallBack;
        }

        @Override
        public void onFlushCompleted(Sensor sensor) {

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            long nowTime=System.currentTimeMillis();
            if (nowTime-mLastTime<mInterval){
                return;
            }
            mLastTime=nowTime;
            //获取x,y,z
            float nowX = event.values[0];
            float nowY = event.values[1];
            float nowZ = event.values[2];
            //计算x,y,z变化量
            float deltaX = nowX - mLastX;
            float deltaY = nowY - mLastY;
            float deltaZ = nowZ - mLastZ;
            //赋值
            mLastX = nowX;
            mLastY = nowY;
            mLastZ = nowZ;
            //计算
            double nowSpeed = Math.sqrt(Double.parseDouble((deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ)+"")) / mInterval * 10000;
            //判断
            if (nowSpeed >= mSpeed) {
                // 开启debug界面
                mShakeCallBack.shake();
            }
        }


    }

    interface ShakeCallBack{
        void shake();
    }
}
